import { ref, computed } from 'vue';
import { TOOLBAR_HEIGHT, STATUS_BAR_HEIGHT, BORDER_HEIGHT, CONTENT_MIN_HEIGHT } from '../utils';

/**
 * 编辑器尺寸调整功能
 */
export function useResize(props, emit) {
  const isResizing = ref(false);
  const startY = ref(0);
  const startHeight = ref(0);
  const currentHeight = ref(props.height || '400px');

  /**
   * 开始调整大小
   */
  const startResize = (e) => {
    isResizing.value = true;
    startY.value = e.clientY;
    
    const heightValue = currentHeight.value;
    if (typeof heightValue === 'number') {
      startHeight.value = heightValue;
    } else if (typeof heightValue === 'string') {
      const parsed = parseInt(heightValue);
      startHeight.value = isNaN(parsed) ? 400 : parsed;
    } else {
      startHeight.value = 400;
    }
    
    document.addEventListener('mousemove', handleResize);
    document.addEventListener('mouseup', stopResize);
  };

  /**
   * 处理调整大小
   */
  const handleResize = (e) => {
    if (!isResizing.value) return;
    
    const deltaY = e.clientY - startY.value;
    const newHeight = startHeight.value + deltaY;
    
    const minHeight = TOOLBAR_HEIGHT + STATUS_BAR_HEIGHT + BORDER_HEIGHT + CONTENT_MIN_HEIGHT;
    const finalHeight = Math.max(minHeight, newHeight);
    
    currentHeight.value = finalHeight;
    emit('resize', finalHeight);
  };

  /**
   * 停止调整大小
   */
  const stopResize = () => {
    isResizing.value = false;
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
  };

  /**
   * 计算容器高度
   */
  const containerHeight = computed(() => {
    if (props.height === 'auto') {
      return 'auto';
    }
    const height = currentHeight.value;
    if (typeof height === 'number' || !isNaN(Number(height))) {
      return `${height}px`;
    }
    return height;
  });

  /**
   * 计算内容区域高度
   */
  const contentHeight = computed(() => {
    if (props.height === 'auto') {
      return 'auto';
    }
    
    const height = currentHeight.value;
    const deductHeight = (props.showStatusBar ? STATUS_BAR_HEIGHT : 0) + TOOLBAR_HEIGHT + BORDER_HEIGHT;
    
    if (typeof height === 'number') {
      return `${Math.max(CONTENT_MIN_HEIGHT, height - deductHeight)}px`;
    }
    
    const parsed = parseInt(height);
    if (!isNaN(parsed)) {
      return `${Math.max(CONTENT_MIN_HEIGHT, parsed - deductHeight)}px`;
    }
    
    if (typeof height === 'string') {
      return `calc(${height} - ${deductHeight}px)`;
    }
    
    return 'auto';
  });

  return {
    // 状态
    isResizing,
    currentHeight,
    containerHeight,
    contentHeight,

    // 方法
    startResize,
    handleResize,
    stopResize,
  };
}
